import Vue from 'vue'
import Loading from './loading.vue'

const Mask = Vue.extend(Loading)

const toggleLoading = (el, binding) => {
	if (binding.value) {
		Vue.nextTick(() => {
			// 控制loading组件显示
			el.instance.visible = true
			// 插入到目标元素
			insertDom(el, el, binding)
		})
	} else {
		el.instance.visible = false
	}
}

const insertDom = (parent, el) => {
	// 给父元素加个定位，让loading元素定位
	el.style.position = 'relative'
	parent.appendChild(el.mask)
}

export default {
	install (Vue) {
		Vue.directive('customLoading',
			{
				bind: function (el, binding, vnode) {
					const mask = new Mask({
						el: document.createElement('div'),
						data () { }
					})
					el.instance = mask
					el.mask = mask.$el
					el.maskStyle = {}
					binding.value && toggleLoading(el, binding)
				},
				update: function (el, binding) {
					if (binding.oldValue !== binding.value) {
						toggleLoading(el, binding)
					}
				},
				unbind: function (el, binding) {
					el.style.position = ''
					el.instance && el.instance.$destroy()
				}
			}
		) // 全局loading
	}
}
